<?php


namespace App\Console\Commands;

use App\Sys\Services\SysI18nService;
use Illuminate\Console\Command;

class I18nCommand extends Command
{
    /**
     * @var string
     */
    private $appId = 'exhibitor_api';
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'i18n {module?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '自动推送资源到数据库';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $i18nService = app()->make(SysI18nService::class);
        $module = $this->argument('module');
        $phpResources = [];
        $dbResources = [];
        $dbResourceMap = [];
        if ($module) {
            $phpResources = include base_path('resources').'/lang/zh-cn/'.$module.".php";
            $dbResources = $i18nService->getAppResource($this->appId, $module);
            foreach ($dbResources as &$r) {
                $r = (array)$r;
                $dbResourceMap[$r['module'].'.'.$r['key']] = $r;
            }
            $tmpResources = [];
            foreach ($phpResources as $key => &$r) {
                $r['module'] = $module;
                $tmpResources[$module.'.'.$key] = $r;
            }
            $phpResources = $tmpResources;
        } else {
            $dbResources = $i18nService->getAppResource($this->appId);
            foreach ($dbResources as &$r) {
                $r = (array)$r;
                $dbResourceMap[$r['module'].'.'.$r['key']] = $r;
            }
            $resourcePath = base_path('resources').'/lang/zh-cn/';
            $resourceIter = new \DirectoryIterator($resourcePath);
            foreach ($resourceIter as $s) {
                if (!$s->isDir()) {
                    $tmp = explode('.', $s->getBaseName());
                    $module = $tmp[0];
                    $pr = include_once base_path('resources').'/lang/zh-cn/'.$module.".php";
                    foreach ($pr as $k=>&$v) {
                        $v['module'] = $module;
                        $phpResources[$module.'.'.$k] = $v;
                    }
                }
            }
        }
        // 1.本地新增的资源同步到数据库
        $insertResList = [];
        foreach ($phpResources as $key=>&$res) {
            $key = explode('.', $key);
            $key = $key[1];
            if (empty($dbResourceMap[$res['module'].'.'.$key])) {
                // 数据库不存在测添加
                $insertResList[] = [
                    'app_id'=>$this->appId,
                    'app_type'=>'php',
                    'module'=>$res['module'],
                    'code'=>$res[0],
                    'key'=>$key,
                    'zh_cn'=>$res[1]
                ];
            }
        }
        if ($insertResList) {
            echo "新增：".count($insertResList).PHP_EOL;
            $i18nService->saveAll($insertResList);
        }
        // 2.数据库的资源同步到本地
        $localResourceCache = [];
        $langList = [
            'zh_cn'=>'zh-cn',
            'en_us'=>'en-us'
        ];
        $modules = [];
        foreach ($dbResources as &$res) {
            $modules[$res['module']] = $res['module'];
        }
        foreach ($modules as $m) {
            foreach ($langList as $k=>$lang) {
                $filePath = base_path('resources').'/lang/'.$lang.'/'.$m.".php";
                if (file_exists($filePath)) {
                    $localResourceCache[$k.'.'.$m] = include base_path('resources').'/lang/'.$lang.'/'.$m.".php";
                }
            }
        }
        foreach ($dbResources as &$res) {
            foreach ($langList as $k=>$lang) {
                if (!empty(trim($res[$k]))) {
                    $localResourceCache[$k.'.'.$res['module']][$res['key']] = [
                        $res['code'],
                        $res[$k]
                    ];
                }
            }
        }
        foreach ($localResourceCache as $k=>&$cache) {
            $lang = explode('.', $k)[0];
            if ($lang == 'zh_cn') {
                continue;
            }
            $fileContent = '<?php'.PHP_EOL.'return ['.PHP_EOL;
            foreach ($cache as $cacheKey=>$cacheVal) {
                $cacheVal[1] = str_replace("'", "\'", $cacheVal[1]);
                $fileContent .= "    '$cacheKey' => [{$cacheVal[0]}, '{$cacheVal[1]}'],".PHP_EOL;
            }
            $fileContent .= '];';
            $langDir = base_path('resources').'/lang/'.$langList[$lang];
            if (!file_exists($langDir)) {
                mkdir($langDir);
            }
            $filePath = $langDir .'/'.explode('.', $k)[1].'.php';
            file_put_contents($filePath, $fileContent);
        }
        echo 'document create successful.'.PHP_EOL;
    }
}
